package cn.uncode.rpc.common.log;

import java.io.File;
import java.util.List;

import cn.uncode.rpc.spi.ExtensionLoader;
import cn.uncode.rpc.util.CollectionUtil;



/**
 * 日志输出器工厂
 */
public class LoggerFactory {

	private LoggerFactory() {
	}

	private static volatile LoggerAdapter LOGGER_ADAPTER = null;
	
	public static void setLoggerAdapter(String loggerAdapter) {
	    if (loggerAdapter != null && loggerAdapter.length() > 0) {
	        setLoggerAdapter(ExtensionLoader.getExtensionLoader(LoggerAdapter.class).getExtension(loggerAdapter));
	    }
	}

	/**
	 * 设置日志输出器供给器
	 * 
	 * @param loggerAdapter
	 *            日志输出器供给器
	 */
	public static void setLoggerAdapter(LoggerAdapter loggerAdapter) {
		if (loggerAdapter != null) {
			Logger logger = loggerAdapter.getLogger(LoggerFactory.class.getName());
			logger.info("using logger: " + loggerAdapter.getClass().getName());
			LoggerFactory.LOGGER_ADAPTER = loggerAdapter;
		}
	}

	/**
	 * 获取日志输出器
	 * 
	 * @param key
	 *            分类键
	 * @return 日志输出器, 后验条件: 不返回null.
	 */
	public static Logger getLogger(Class<?> clazz) {
		if(LOGGER_ADAPTER == null){
			List<LoggerAdapter> LoggerAdapters = ExtensionLoader.getExtensionLoader(LoggerAdapter.class).getExtensions(null);
			if(!CollectionUtil.isEmpty(LoggerAdapters)){
				LOGGER_ADAPTER = LoggerAdapters.get(0);
			}
		}
		return new ProxyLogger(LOGGER_ADAPTER.getLogger(clazz));
	}

	/**
	 * 获取日志输出器
	 * 
	 * @param key
	 *            分类键
	 * @return 日志输出器, 后验条件: 不返回null.
	 */
	public static Logger getLogger(String key) {
		if(LOGGER_ADAPTER == null){
			List<LoggerAdapter> LoggerAdapters = ExtensionLoader.getExtensionLoader(LoggerAdapter.class).getExtensions(null);
			if(!CollectionUtil.isEmpty(LoggerAdapters)){
				LOGGER_ADAPTER = LoggerAdapters.get(0);
			}
		}
		return new ProxyLogger(LOGGER_ADAPTER.getLogger(key));
	}
	
	/**
	 * 动态设置输出日志级别
	 * 
	 * @param level 日志级别
	 */
	public static void setLevel(Level level) {
		LOGGER_ADAPTER.setLevel(level);
	}

	/**
	 * 获取日志级别
	 * 
	 * @return 日志级别
	 */
	public static Level getLevel() {
		return LOGGER_ADAPTER.getLevel();
	}
	
	/**
	 * 获取日志文件
	 * 
	 * @return 日志文件
	 */
	public static File getFile() {
		return LOGGER_ADAPTER.getFile();
	}

}